package implementation.logger;

import java.io.IOException;
import java.util.Date;

import org.apache.log4j.*;
import org.apache.log4j.helpers.DateLayout;
import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.LoggingEvent;

/**
 * use:
 * Logger log = CLoggerFactory.getFileLogger(name,filename)
 * log.info("message");
 * log.debug("kjhkj");
 * db logging not yet working
 * @author Administrator
 */

public class CLoggerFactory {

	public CLoggerFactory(){

	}
	
	public static Logger getFileLogger(String name, String fn) throws IOException{
		Logger ret = Logger.getLogger(name);
		Layout sLayout = new DateLayout() {
			
			@Override
			public boolean ignoresThrowable() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public String format(LoggingEvent arg0) {
				String frmt = new Date(arg0.timeStamp).toString() + " " + arg0.getLoggerName() + "\n";
				frmt = frmt + arg0.getLevel().toString() + " - " + arg0.getMessage() + "\n";
				return frmt;
			}
		};
		Appender fileApp = null;
		fileApp = new FileAppender(sLayout,fn);
		if (fileApp!=null){
			ret.addAppender(fileApp);
		}
		return ret;
	}
	
	public static Logger getDBLogger(String name, String url){
		Logger ret = Logger.getLogger(name);
		//Layout sLayout = new SimpleLayout();
		JDBCAppender jdbcApp = new JDBCAppender();
		jdbcApp.setURL(url);
		jdbcApp.setSql("INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m')");
		
		ret.addAppender(jdbcApp);
		return ret;
	}
	//example:
	/*
	public static void main(String[] args){
		Logger l = null;
		try {
			 l = CLoggerFactory.getFileLogger("testlog", "test.log");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		l.info("test info");
		l.debug("test debug");
	}
	*/
}
